import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.joints.DistanceJoint;
import pulpcore.animation.BindFunction;
import pulpcore.math.CoreMath;
import pulpcore.sprite.Group;
import pulpcore.sprite.Sprite;
import pulpfizz.physics.BodyUtils;
import pulpfizz.physics.JointUtils;
import pulpfizz.physics.Material;
import pulpfizz.pulp.body.BodySprite;
import pulpfizz.pulp.body.ImageBodySprite;
import pulpfizz.pulp.body.Java2DBodySprite;

import java.awt.*;

/**
 * Created by will
 * Date: May 21, 2008 11:30:02 PM
 */
public class Creature extends Group {

    Group creatureShadow = new Group();
    public Creature(Arena arena, float cy) {
        Material m = Material.RANDOM();
        Body prevBody = null;
        float r = (float) CoreMath.rand(0.2, 0.4);
        for (int i = -8; i < 8; i++)
        {
            Body body = BodyUtils.createCircle(arena.getWorld(), i * (.14f + r), -cy * 0.5f, r);
            m.applyAll(body);
            body.setBullet(true);
            ImageBodySprite creature;
                creature = new ImageBodySprite(body, arena, "caterpillar.png");
            Color greyshadow = new Color(50, 50, 50, 100);

            Java2DBodySprite shadow = new Java2DBodySprite(body, arena,1,greyshadow,greyshadow,greyshadow);
            shadow.x.bindTo(creaturePosX(creature));
            shadow.y.bindTo(creaturePosY(creature));
//            shadow.angle.bindTo(this.angle);
            shadow.alpha.bindTo(this.alpha);

            creatureShadow.add(shadow);
            this.add(creature);

            m.applyAll(body);
            if (prevBody != null)
            {
                DistanceJoint jd = JointUtils.distanceJoint(body,prevBody);
                //				jd.m_frequencyHz = 6f;
                jd.m_frequencyHz = 50f;
                jd.m_dampingRatio = 0.5f;
            }
            if (i == 7)
                prevBody = null;
            else
                prevBody = body;
        }
    }

    BindFunction creaturePosX(final BodySprite creature) {
        return new BindFunction() {
            public Number f() {
                return (creature.posX(creature.getBody()).f().doubleValue() +3);
            }
        };
    }
    BindFunction creaturePosY(final BodySprite creature) {
        return new BindFunction() {
            public Number f() {
                return (creature.posY(creature.getBody()).f().doubleValue() +3);
            }
        };
    }


    public Sprite getShadow() {
        return creatureShadow;
    }
}
